<template>
  <a-drawer
    title="权限管理"
    :width="860"
    :visible="visible"
    :maskClosable="false"
    @close="close()">

    <a-alert type="info" showIcon style="margin-bottom: 16px;">
      <template slot="message">
        <span>已选择</span>
        <a style="font-weight: 600;padding: 0 4px;">{{ table.selectedRowIds.length }}</a>
        <span>项</span>
        <template v-if="table.selectedRowIds.length>0">
          <a-divider type="vertical"/>
          <a @click="handleClearSelection">清空</a>
          <a-divider type="vertical"/>
          <a-popconfirm :title="`确定要删除这 ${table.selectedRowIds.length} 项吗?`" @confirm="handleClickDeleteBatch">
            <a>批量删除</a>
          </a-popconfirm>
        </template>
      </template>
    </a-alert>

    <j-editable-table ref="jet" rowNumber rowSelection v-bind="table" @selectRowChange="table.selectedRowIds=$event">

      <template v-slot:action="props">
        <div style="text-align: right">
          <template v-if="editAuthIsShow(props)">
            <a @click="handleClickEditAuth(props)">编辑权限</a>
            <a-divider type="vertical"/>
          </template>
          <a-popconfirm title="确定要删除吗?" placement="left" @confirm="handleClickDelete(props)">
            <a>删除</a>
          </a-popconfirm>
        </div>
      </template>

    </j-editable-table>

    <a-modal
      title="编辑权限"
      :width="800"
      :visible="modal2.visible"
      :maskClosable="false"
      @ok="handleEditAuthOk"
      @cancel="modal2.visible=false">

      <a-form>
        <a-form-item label="用户权限">
          <j-select-multi-user v-model="userValues"/>
        </a-form-item>
        <a-form-item label="角色权限">
          <j-select-role v-model="roleValues"/>
        </a-form-item>
        <a-form-item label="部门权限">
          <j-select-depart v-model="departValues" multi/>
        </a-form-item>
      </a-form>

    </a-modal>

    <div class="drawer-bottom">
      <a-button style="margin-right: 8px" @click="close()">取消</a-button>
      <a-button @click="handleOk" type="primary" :loading="table.loading">确定</a-button>
    </div>

  </a-drawer>
</template>

<script>
  import { getAction, postAction, deleteAction, httpAction } from '@/api/manage'
  import { FormTypes } from '@/utils/JEditableTableUtil'
  import JEditableTable from '@/components/jeecg/JEditableTable'
  import JSelectDepart from '@/components/jeecgbiz/JSelectDepart'
  import JSelectMultiUser from '@/components/jeecgbiz/JSelectMultiUser'
  import JSelectRole from '@/components/jeecgbiz/JSelectRole'

  export default {
    name: 'DesignFormAuthModal',
    components: { JEditableTable, JSelectDepart, JSelectMultiUser, JSelectRole },
    data() {
      return {
        visible: false,
        model: {},
        currentRowId: '',
        userValues: null,
        roleValues: null,
        departValues: null,

        table: {
          loading: false,
          columns: [
            {
              key: 'authTitle',
              title: '权限名称',
              type: FormTypes.normal,
              width: '180px',
              props: { readonly: true }
            },
            {
              key: 'authField',
              title: '权限字段',
              type: FormTypes.normal,
              width: '250px',
              props: { readonly: true }
            },
            {
              key: 'authType',
              title: '授权类型',
              width: '180px',
              type: FormTypes.select,
              options: [],
              dictCode: 'form_perms_type',
              placeholder: '请选择${title}'
            },
            {
              key: 'authScopeIsAll',
              title: '授权给所有人',
              width: '50px',
              type: FormTypes.checkbox,
              customValue: ['Y', 'N']
              // type: FormTypes.select,
              // options: [
              //   { text: '所有人', value: 'Y' },
              //   { text: '非所有人', value: 'N' }
              // ],
            },
            {
              key: 'action',
              title: '操作',
              width: '130px',
              type: FormTypes.slot,
              slotName: 'action',
            },
            { key: 'authComKey', type: FormTypes.hidden },
            { key: 'authScopeUsersVal', type: FormTypes.hidden },
            { key: 'authScopeRolesVal', type: FormTypes.hidden },
            { key: 'authScopeDepartsVal', type: FormTypes.hidden },
          ],
          dataSource: [],
          // 被选中行的id
          selectedRowIds: []
        },
        modal2: {
          visible: false
        },
        url: {
          query: (desformCode) => `/desform/auth/query/${desformCode}`,
          updateBatch: '/desform/auth/updateBatch',
          deleteByComKey: '/desform/auth/deleteByComKey',
          deleteBatch: '/desform/auth/deleteBatch'
        }
      }
    },
    computed: {},
    created() {

    },
    methods: {

      loadAuthList() {
        this.table.loading = true
        getAction(this.url.query(this.model.desformCode)).then((res) => {
          if (res && res.success) {
            this.table.dataSource = res.result
          }
        }).finally(() => {
          this.table.loading = false
        })
      },

      open(record) {
        this.visible = true
        this.table.dataSource = []
        // todo 定义 model
        this.model = record

        this.loadAuthList()
      },

      close() {
        this.visible = false
      },

      handleOk() {
        let { values } = this.$refs.jet.getValuesSync({ validate: false })

        if (values.length <= 0) {
          this.close()
          return
        }

        this.table.loading = true
        postAction(this.url.updateBatch, values).then(res => {
          if (res && res.success) {
            this.$message.success('修改成功')
            this.close()
          } else {
            this.$message.error('修改失败：' + res.message)
          }
        }).finally(() => {
          this.table.loading = false
        })
      },

      handleClickEditAuth(props) {
        let rowValue = props.getValue()

        this.userValues = rowValue['authScopeUsersVal']
        this.roleValues = rowValue['authScopeRolesVal']
        this.departValues = rowValue['authScopeDepartsVal']
        this.currentRowId = props.rowId

        this.modal2.visible = true
      },

      handleClickDelete(props) {
        let { getValue } = props, rowValue = getValue(), { authComKey } = rowValue

        this.__deleteCommonThen(httpAction(this.url.deleteByComKey, { desformCode: this.model.desformCode, authComKey }, 'DELETE'))
      },

      handleClickDeleteBatch() {
        this.__deleteCommonThen(deleteAction(this.url.deleteBatch, { ids: this.table.selectedRowIds.join(',') }))
      },

      __deleteCommonThen(promise) {
        this.table.loading = true
        let success = false
        promise.then(res => {
          if (res.success) {
            this.$message.success('删除成功')
            success = true
            this.loadAuthList()
          } else {
            console.error(res)
            this.$message.warn('删除失败：' + res.message)
          }
        }).catch(e => {
          console.error(e)
          this.$message.error('删除失败')
        }).finally(() => {
          if (!success) this.table.loading = false
        })
      },

      editAuthIsShow(props) {
        let { caseId, rowId, allValues: { checkboxValues } } = props
        return checkboxValues[`authScopeIsAll${caseId}${rowId}`] === false
      },

      handleEditAuthOk() {
        this.$refs.jet.setValues([
          {
            rowKey: this.currentRowId,
            values: {
              authScopeUsersVal: this.userValues,
              authScopeRolesVal: this.roleValues,
              authScopeDepartsVal: this.departValues
            }
          }
        ])

        this.modal2.visible = false
      },

      handleClearSelection() {
        this.$refs.jet.clearSelection()
      }

    }
  }
</script>

<style lang="scss" scoped>
  .drawer-bottom {
    position: absolute;
    bottom: 0;
    width: 100%;
    border-top: 1px solid #e8e8e8;
    padding: 10px 16px;
    text-align: right;
    left: 0;
    background: #fff;
    border-radius: 0 0 4px 4px;
  }
</style>